<template>
	<div>
		<van-cell-group>
		  <van-cell title="头像" class="avatar">
				<template #right-icon>
					<div class="avatar-wrapper">
						<img v-lazy="userinfo.userImg" alt="用户头像">
						<van-uploader class="up-userbg" :after-read="afterRead" />
					</div>
				</template>
			</van-cell>
			 <van-cell title="用户Id" :value="userinfo.userId" />
			 <van-cell title="手机号" :value="userinfo.phone" />
			 <van-field
			   v-model="userinfo.nickName"
			   label="昵称"
			   placeholder="输入昵称"
			   input-align="right"
				 clearable
				 @blur="updateNickName"
			 />
			 <van-field
			   v-model="userinfo.desc || '这家伙很懒，什么都没写！'"
			   label="简介"
			   placeholder="输入简介"
			   input-align="right"
				 clearable
				 @blur="updateDesc"
			 />
		</van-cell-group>
	</div>
</template>

<script>
	import bus from '@/utils/eventBus.js'
	import { 
		getUserInfoAll, 
		updateUserAvatar,
		updateNickName,
		updateDesc
	} from '@/api/user.js'
	export default {
		data () {
			return {
				userinfo: {}
			}
		},
		created() {
			this._getUserInfoAll()
		},
		methods: {
			// 图片上传钩子函数
			afterRead(file) {
				console.log(file)
				// 允许格式
				let type = ["gif", "png", "jpg", "jpeg"]
				// 图片允许大小 1MB
				let size = 1
				// 获取文件后缀
				let fileType = file.file.type.split('/')[1]
				console.log('图片类型',fileType)
				console.log('图片是非符合规则',type.includes(fileType))
				// 判断后缀是否符合要求
				if (!type.includes(fileType)) return this.$toast(`当前文件格式不支持,仅支持${type.join(",")}`)
				// 获取图片大小 (单位为MB)
				let fileSize = file.file.size / 1024 / 1024
				console.log('图片大小',fileSize)
				if (fileSize > size) return this.$toast(`文件不允许超过${size}MB`)
				// 提取base64编码 replace(规定子字符串或要替换的模式的 RegExp 对象,一个字符串值。规定了替换文本或生成替换文本的函数。)
				let base64 = file.content.replace(/^data:image\/[A-Za-z]+;base64,/, "")
				// 判断 token
				const tokenString = window.sessionStorage.getItem('token')
				if(!tokenString) return this.$router.push({name: 'Login'})
				this.$toast.loading({
					message: '上传中···',
					forbidClick: true
				})
				// 发起请求
				updateUserAvatar({
					tokenString,
					imgType: fileType,
					serverBase64Img: base64
				})
				.then(({data: res}) => {
					this.$toast.clear()
					console.log('上传用户头像',res)
					if (res.code !== 'H001') return this.$router.push({ name: "Login" })
					// 查询获取用户信息
					this._getUserInfoAll()
				})
			},
			// 获取用户完整信息
			_getUserInfoAll () {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				getUserInfoAll({
					tokenString
				})
				.then(({data: res}) => {
					console.log('用户完整信息',res)
					if (res.code !== 'B001') return this.$toast.fail('获取用户信息异常,请重新尝试!')
					this.userinfo = res.result[0]
					const userInfo = JSON.stringify(res.result[0])
					window.sessionStorage.setItem('userInfoAll',userInfo)
					bus.$emit('refresh-userinfo')
				})
				.catch(err => {
					this.$toast.fail('获取用户信息失败,请重新尝试!')
				})
			},
			// 更新用户昵称
			async updateNickName() {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				// 获取原昵称
				const beforeNickName = JSON.parse(window.sessionStorage.getItem('userInfo')).nickName
				if (!this.userinfo.nickName) {
					this.$toast.fail('修改失败,昵称不能为空!')
					this.userinfo.nickName = beforeNickName
					return
				}
				// 提示框
				const resultConfirm = await this.$dialog.confirm({
					message: '是否修改昵称',
					confirmButtonColor: '#3498db'
				}).catch(err => err)
				// 判断是点击确定还是取消
				if (resultConfirm !== 'confirm') return this.userinfo.nickName = beforeNickName
				
				this.$toast.loading({
					message: '修改中···',
					forbidClick: true
				})
				updateNickName({
					tokenString,
					nickName: this.userinfo.nickName
				})
				.then(({data: res}) => {
					console.log('修改用户昵称',res)
					if (res.code !== 'C001') {
						this.$toast.fail('修改异常,请重新尝试!')
						this.userinfo.nickName = beforeNickName
						return 
					}
					this.$toast.success(res.msg)
					this._getUserInfoAll()
				})
				.catch(err => {
					this.$toast.fail('修改失败,请重新尝试!')
					this.userinfo.nickName = beforeNickName
				})
			},
			// 更新用户简介
			async updateDesc() {
				const tokenString = window.sessionStorage.getItem('token')
				if (!tokenString) return this.$router.push({ name: "Login" })
				// 获取原简介
				const beforeDesc = JSON.parse(window.sessionStorage.getItem('userInfo')).desc
				// 提示框
				const resultConfirm = await this.$dialog.confirm({
					message: '是否修改简介',
					confirmButtonColor: '#3498db'
				}).catch(err => err)
				// 判断是点击确定还是取消
				if (resultConfirm !== 'confirm') return this.userinfo.desc = beforeDesc
				
				this.$toast.loading({
					message: '修改中···',
					forbidClick: true
				})
				updateDesc({
					tokenString,
					desc: this.userinfo.desc
				})
				.then(({data: res}) => {
					console.log('修改用户简介',res)
					if (res.code !== 'D001') {
						this.$toast.fail('修改异常,请重新尝试!')
						this.userinfo.nickName = beforeNickName
						return 
					}
					this.$toast.success(res.msg)
					this._getUserInfoAll()
				})
				.catch(err => {
					this.$toast.fail('修改失败,请重新尝试!')
					this.userinfo.desc = beforeDesc
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.van-cell-group{
		&::after{
			border: none;
		}
		.avatar{
			align-items: center;
			.avatar-wrapper {
				width: 40px;
				height: 40px;
				position: relative;
				img {
					width: 100%;
					height: 100%;
					object-fit: cover;
					border-radius: 50%;
				}
				.up-userbg{
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					opacity: 0;
					/deep/ .van-uploader__wrapper{
						width: 100%;
						height: 100%;
						/deep/ .van-uploader__upload{
							margin: 0;
							width: 100%;
							height: 100%;
						}
					}
				}
			}
		}
		
		/deep/ .van-field__control{
			color: #969799;
		}
	}
</style>